/**
 * Progress Bar Control.
 *
 * @author Andrey Anisimov <hercules@inbox.ru>
 * @see core.ui.ScrollBar, core.ui.Slider
 */

import core.ui.Window;

class ProgressBar extends Window {

	this.ProgressBar = function(parent, x, y, width, height) {
		super(parent, x, y, width, height);
		this.pos = 0;
		this.rangeMax = 100;
		this.rangeMin = 0;
		this.current = 0;
		this.items = [];
	}

	/**
	 * Sets the progress range.
	 * 
	 * @param min, max (int) progress limits (0, 100 by default).
	 */
	this.setRange = function(min, max) {
		this.rangeMin = min;
		this.rangeMax = max;
		this.setPos(min);
	}
	
	/**
	 * Gets the minimum progress range.
	 *
	 * @return int
	 */
	this.getRangeMin = function() {
		return this.rangeMin;
	}
	
	/**
	 * Gets the maximum progress range.
	 *
	 * @return int
	 */
	this.getRangeMax = function() {
		return this.rangeMax;
	}
	
	/**
	 * Sets the count of items in progress.
	 * 
	 * @param count (int) count of items.
	 */
	this.setItemCount = function(cnt) {
		if (this.items.length == cnt) return;
		// Remove old parts
		while (this.items.length > 0) {
			this.items.pop().close();
		}
		// Add new parts
		for (var i = 0; i < cnt; i++) {
			var part = new Window(this);
			part.getElement().style.styleFloat = part.getElement().style.cssFloat = 'left';
			part.setStyleName('ProgressBarItem');
			part.hide();
			this.items.push(part);
		}
	}
	
	/**
	 * Gets the count of items in progress.
	 *
	 * @return int
	 */
	this.getItemCount = function() {
		return this.items.length;
	}
	
	/**
	 * Goes to next progress step.
	 * Note: used only after setItemCount().
	 */
	this.next = function() {
		var offset = (this.items.length > 0) ? ((this.rangeMax - this.rangeMin) / this.items.length) : 1;
		this.setPos(this.pos + offset);
	}
	
	/**
	 * Sets the current progress position.
	 * 
	 * @param pos (int) progress position (within specified range).
	 */
	this.setPos = function(pos) {
		var i = Math.ceil((this.items.length - 1) * pos / (this.rangeMax - this.rangeMin));
		if (i >= 0 && i < this.items.length) {
			for (var k = this.current; k >= i; k--) this.items[k].hide();
			for (var k = this.current; k <= i; k++) this.items[k].show();
			this.current = i;
		} else if (0 == this.items.length) {
			// Create parts automatically
//			this.current = 0;
		}
		this.pos = pos;
	}
	
	/**
	 * Gets the current progress position.
	 * 
	 * @return int.
	 */
	this.getPos = function() {
		return this.pos;
	}
}